package gu.sql2java.observer.exe.mysql;

import static gu.sql2java.observer.exe.mysql.InstallerConfig.CONFIG;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import gu.sql2java.SimpleLog;
import gu.sql2java.observer.JDBCUtility;
import gu.sql2java.observer.TriggerInstaller;

import static gu.sql2java.observer.JDBCUtility.getTablenames;
import static gu.sql2java.observer.JDBCUtility.createConnection;

public class InstallerMain {
	public static void main(String ...argv) throws SQLException {
		CONFIG.parseCommandLine(argv);
		try(Connection con = createConnection(CONFIG.getJdbcurl(),CONFIG.getUsername(),CONFIG.getPassword(),null)){
			JDBCUtility.checkDatatbaseVersion(con.getMetaData(),"MySQL","5.7",null);
			TriggerInstaller installer = new TriggerInstaller(false);
			if(CONFIG.isUdf()){
				if(CONFIG.isRemove()){
					installer.removeUDF(CONFIG.getJdbcurl(),CONFIG.getUsername(),CONFIG.getPassword());							
				}else{
					installer.installUDF(CONFIG.getJdbcurl(),CONFIG.getUsername(),CONFIG.getPassword());
				}
			}else{				
				List<String> tablenames = getTablenames(con.getMetaData(),null,CONFIG.getSchema(),CONFIG.getTablepattern());
				if(!tablenames.isEmpty()){
					for(String schematable : tablenames){
						if(CONFIG.isRemove()){
							installer.removeTrigger(schematable, CONFIG.getJdbcurl(),CONFIG.getUsername(),CONFIG.getPassword(), null);
						}else {
							installer.installTrigger(schematable, CONFIG.getJdbcurl(),CONFIG.getUsername(),CONFIG.getPassword(), null);
						}
					}
				}else{
					SimpleLog.log("NOT FOUD TABLE for {}.{}",CONFIG.getSchema(),CONFIG.getTablepattern());
				}
			}
				
		}		
	}
}
